<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="auto"
    status-icon
    inline
    @submit.native.prevent="handleSubmit"
  >
    <template v-for="(item, index) in columns" :key="index">
      <el-form-item :label="item.label" :prop="item.prop" :style="item.style">
        <!-- 普通选择器组件 -->
        <el-select
          v-if="item.component === 'el-select'"
          v-model="formData[item.prop]"
          :placeholder="`请选择${item.label}`"
          clearable
          v-bind="item.componentProps || {}"
          style="width: 100%"
          @change="item.onChange"
        >
          <el-option
            v-for="opt in item.options"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          >
            <div v-if="item.showValue">
              <span style="float: left">
                {{ opt.before }}
              </span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                  margin-left: 20px;
                "
              >
                {{ opt.after }}
              </span>
            </div>
          </el-option>
        </el-select>
        <!-- 普通输入组件 -->
        <component
          v-else
          :is="item.component"
          v-model="formData[item.prop]"
          v-bind="item.componentProps || {}"
          style="width: 100%;"
        />
      </el-form-item>
    </template>
    <el-form-item>
      <el-button type="primary" :icon="Search" @click="handleSubmit">查询</el-button>
      <el-button :icon="RefreshRight" @click="handleReset">重置</el-button>
      <slot name="btn" />
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Search, RefreshRight } from '@element-plus/icons-vue'


const props = defineProps({
  columns: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.every(item => {
        const valid = 'label' in item && 'prop' in item
        return valid && (item.options || 'component' in item)
      })
    }
  },
  rules: {
    type: Object,
    default: () => ({})
  },
  formData: {
    type: Object,
    required: true
  },
})

const formRef = ref()
const emits = defineEmits(['submit', 'reset', 'dataExport'])

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    emits('submit', props.formData)
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

const handleReset = () => {
  formRef.value?.resetFields()
  emits('reset')
}

const exReset = () => {
  formRef.value?.resetFields()
}

defineExpose({
  exReset
})
</script>